package com.tianyang.yukuaifu.common.utils;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.net.Uri;
import android.text.TextUtils;

import com.tianyang.yukuaifu.base.YkfApplication;
import com.tianyang.yukuaifu.receiver.MessageOutput;
import com.tianyang.yukuaifu.utils.DateUtils;

/**
 * 通知，消息管理.
 */
public class NoticeUtils {

    public static final int SYSTEM_NOTIFY_ID = 10000;
    public static final int PAY_NOTIFY_ID = 20000;
    public static final int MEMBER_NOTIFY_ID = 30000;


    private static NoticeUtils mNoticeManager;
    private Context mContext;
    private NotificationManager mNotificationManager;
    private long lastNotifyTime;
    private AudioManager mAudioManager;

    private NoticeUtils(Context context) {
        mContext = context;
        mNotificationManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mAudioManager = (AudioManager) mContext.getSystemService(mContext.AUDIO_SERVICE);
    }

    public static NoticeUtils getInstance() {
        if (mNoticeManager == null) {
            mNoticeManager = new NoticeUtils(YkfApplication.getInstance());
        }

        return mNoticeManager;
    }

    public void clearAllNotification() {
        lastNotifyTime = 0;
        mNotificationManager.cancel(SYSTEM_NOTIFY_ID);
        mNotificationManager.cancel(PAY_NOTIFY_ID);
        mNotificationManager.cancel(MEMBER_NOTIFY_ID);
    }

    public void clearNotification(int type) {
        lastNotifyTime = 0;
        mNotificationManager.cancel(type);
    }

    /**
     * 支付消息 通知栏显示
     */
    public void sendPayNotification(MessageOutput output) {
        if (output == null) return;
        Uri uri = Uri.parse(String.format("%s://%s", "PaySuccessActivity", mContext.getPackageName())).buildUpon()
                .appendQueryParameter("amount", output.getPayAmount())
                .appendQueryParameter("isUpgrade", "false")
                .appendQueryParameter("cashAmount", null)
                .appendQueryParameter("currencyName",
                        TextUtils.isEmpty(output.getCurrencyName()) ? "元" : output.getCurrencyName())
                .appendQueryParameter("timestamp", DateUtils.string2Date(output.getPayTime(), "yyyy-MM-dd HH:mm:ss").getTime() + "").build();
        Intent intent = new Intent(String.format("%s.business.trade.view.%s",
                mContext.getPackageName(), "PaySuccessActivity"));
        intent.setData(uri);
        sendNotify(intent, null, output.getTitle(), output.getContent(), output.getTitle(), PAY_NOTIFY_ID, true);
    }

    /**
     * 系统消息->交易模块
     */
    public void sendSystemNotification(String title, String content, String target) {
        Uri uri = Uri.parse(String.format("%s://%s", target, mContext.getPackageName())).buildUpon()
                .appendQueryParameter("title", title)
                .appendQueryParameter("content", content)
                .build();
        Intent intent = new Intent(String.format("%s.business.trade.view.%s", mContext.getPackageName(), target));
        intent.setData(uri);
        sendNotify(intent, null, content, title, content, SYSTEM_NOTIFY_ID, true);
    }

    /**
     * 系统消息->会员模块
     */
    public void sendMemberNotification(String title, String content) {
        Uri uri = Uri.parse(String.format("%s://%s", "MembershipDetailsActivity", mContext.getPackageName())).buildUpon()
                .appendQueryParameter("title", title)
                .appendQueryParameter("content", content)
                .build();
        Intent intent = new Intent(String.format("%s.business.member.view.%s",
                mContext.getPackageName(), "MembershipDetailsActivity"));
        intent.setData(uri);
        sendNotify(intent, null, content, title, content, MEMBER_NOTIFY_ID, true);
    }

    /**
     * 系统消息
     */
    public void sendSystemNotification(String title, String content) {
        Uri uri = Uri.parse(String.format("%s://%s", "MainActivity", mContext.getPackageName())).buildUpon()
                .appendQueryParameter("title", title)
                .appendQueryParameter("content", content)
                .build();
        Intent intent = new Intent(String.format("%s.business.main.view.%s", mContext.getPackageName(), "MainActivity"));
        intent.setData(uri);
        sendNotify(intent, null, content, title, content, SYSTEM_NOTIFY_ID, true);
    }

    @SuppressLint("NewApi")
    private void sendNotify(Intent intent, Bitmap bitmap, String tickerText,
                            String contentTitle, String contentText, int notifyId, boolean needSound) {
        Notification.Builder builder;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            String channelId = "simple";
            NotificationChannel channel = new NotificationChannel(channelId, "simple", NotificationManager.IMPORTANCE_DEFAULT);
            mNotificationManager.createNotificationChannel(channel);
            builder = new Notification.Builder(mContext, channelId);
        } else {
            builder = new Notification.Builder(mContext);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent appIntent = PendingIntent.getActivity(mContext, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(appIntent);
        // General settings
        if (bitmap == null || bitmap.isRecycled()) {
            bitmap = BitmapFactory.decodeResource(mContext.getResources(),
                    mContext.getResources().getIdentifier("ic_launcher", "mipmap", mContext.getPackageName()));
        }
        builder.setLargeIcon(bitmap);
        // 设置顶部状态栏的小图标
        int smallIcon = 0;
        if (android.os.Build.VERSION.SDK_INT < 21) {
            smallIcon = mContext.getResources().getIdentifier("ic_launcher", "mipmap", mContext.getPackageName());
        } else if (android.os.Build.VERSION.SDK_INT == 21) {
            smallIcon = mContext.getResources().getIdentifier("ic_notification", "mipmap", mContext.getPackageName());
        } else {
            smallIcon = mContext.getResources().getIdentifier("ic_notification_dark", "mipmap", mContext.getPackageName());
        }
        builder.setSmallIcon(smallIcon);
        builder.setTicker(tickerText);// 首次收到的时候，在状态栏中，图标的右侧显示的文字
        builder.setContentTitle(contentTitle);// 设置通知中心的标题
        builder.setContentText(contentText);// 设置通知中心中的内容

        builder.setAutoCancel(true);
        builder.setDefaults(Notification.DEFAULT_ALL);//打开呼吸灯，声音，震动，触发系统默认行为
        builder.setPriority(Notification.PRIORITY_DEFAULT);
        /*Notification.DEFAULT_VIBRATE    //添加默认震动提醒  需要VIBRATE permission
        Notification.DEFAULT_SOUND    //添加默认声音提醒
        Notification.DEFAULT_LIGHTS//添加默认三色灯提醒
        Notification.DEFAULT_ALL//添加默认以上3种全部提醒*/
        //.setLights(Color.YELLOW, 300, 0)//单独设置呼吸灯，一般三种颜色：红，绿，蓝，经测试，小米支持黄色
        //.setSound(url)//单独设置声音
        //.setVibrate(new long[] { 100, 250, 100, 250, 100, 250 })//单独设置震动


        //比较手机sdk版本与Android 5.0 Lollipop的sdk
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {

          /*android5.0加入了一种新的模式Notification的显示等级，共有三种：
          VISIBILITY_PUBLIC只有在没有锁屏时会显示通知
          VISIBILITY_PRIVATE任何情况都会显示通知
          VISIBILITY_SECRET在安全锁和没有锁屏的情况下显示通知*/
            builder
                    .setVisibility(Notification.VISIBILITY_PUBLIC)
                    .setCategory(Notification.CATEGORY_MESSAGE)//设置通知类别
                    //.setColor(context.getResources().getColor(R.color.small_icon_bg_color))//设置smallIcon的背景色
                    .setFullScreenIntent(appIntent, true);//将Notification变为悬挂式Notification，使用这种模式的时候，activity 必须处于全屏状态，否则无效
        }

        long curTime = System.currentTimeMillis();

        if (curTime - lastNotifyTime > 2500) {//短时间内连续的消息。没有声音和震动
            boolean needVibrate = false;
            switch (mAudioManager.getRingerMode()) {
                case AudioManager.RINGER_MODE_SILENT:
                    needVibrate = needSound = false;
                    break;
                case AudioManager.RINGER_MODE_VIBRATE:
                case AudioManager.RINGER_MODE_NORMAL:
                    needVibrate = true;
                    break;
            }

            if (needSound) {
                builder.setDefaults(Notification.DEFAULT_SOUND);
            }
            if (needVibrate) {
                long[] vibrate = new long[]{
                        300, 100, 300, 100
                };
                builder.setVibrate(vibrate);
            }
            lastNotifyTime = curTime;
        }
        mNotificationManager.notify(notifyId, builder.build());
    }
}
